# -*- coding: utf-8 -*-


# cmap2owl -- Helper application to convert from concept maps to OWL ontologies
# Copyright (c) 2008-2013  Rodrigo Rizzi Starr
#  
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


'''
Generates a question with multiple options

@author: Rodrigo Rizzi Starr
@copyright: Copyright © 2008-2013 Rodrigo Rizzi Starr
@license: MIT License
@contact: rodrigo.starr@gmail.com
'''


import sys

# GTK+ imports
import pygtk
if not sys.platform == 'win32':
    pygtk.require('2.0')
try:
    import gtk
except:
    sys.exit(1)

from CMap2Prolog import assemblyQuery
from mapperQuestion import MapperQuestion, clickBehaviour
from log import log
log.debug("Loaded...")

class MultiQuestion(MapperQuestion):
    """Allows the appearance of a question with more options than yes or no.
        The options should be mutually exclusive.
        
        When called, query must be a dictionary with key the name to be put in
        the button and with value the query. The buttons will be in alphabetical
        order"""
    
    def __init__(self,
                 db,
                 data,
                 question = "",
                 query = {},
                 helpFile = "basic",
                 noneCondition = ""):

        MapperQuestion.__init__(self,
                                db,
                                data,
                                question,
                                query,
                                helpFile = helpFile,)
        self.noneCondition = noneCondition
        self.bNone = None
        
    def updateSensitivity(self):
        "Updates the none button state"
        super(MultiQuestion, self).updateSensitivity()
        
        # If we have a special condition for none, test it
        if self.noneCondition != '':
            query = assemblyQuery(self.noneCondition, self.data)
            result = self.db.query(query)
            try:
                result.next()
            except StopIteration: # So none is valid
                self.bNone.set_sensitive(self.label.get_property("sensitive"))
            else: # So none is not valid
                self.bNone.set_sensitive(False)
        
        
    def updateQueryData(self):
        "Creates a string representing a query"
        self.queryData = 'possible(%s)' % \
                assemblyQuery(self.queryTemplate.values()[0], self.data)
    
    def createButtons(self):
        "Returns a list with the buttons that MapperQuestion will use"
        
        buttons = []
        keys =  self.queryTemplate.keys()
        keys.sort()
        
        for key in keys:
            button = gtk.Button(key)
            button.connect("clicked", self.onClicked)
            button.connect("button-press-event", self.onButtonPress)
            buttons.append(button)
        
        self.bNone = gtk.Button("None")
        self.bNone.connect("clicked", self.onNone)
        self.bNone.connect("button-press-event", self.onButtonPress)
        
        buttons.append(self.bNone)
        
        return buttons
      
    @clickBehaviour
    def onClicked(self, widget):
        "Assert the concept corresponding to the button clicked"
        
        action = self.queryTemplate[widget.get_label()]
        
        queries = [assemblyQuery("isTrue(" + action + ")", **self.data)]
        self.assertz(queries)
        return False
      
    @clickBehaviour
    def onNone(self, widget):
        "Answer when the choice was an individualization"
        
        queries = []
        for action in self.queryTemplate.itervalues():
            queries.append(assemblyQuery("isFalse(" + action + ")",
                                          **self.data))
            
        self.assertz(queries)
            
        return False
      
